/*
 * Copyright (c) Ulrich Hilger, http://dev.uhilger.de, all rights reserved.
 *
 * Published under the terms and conditions of the Apache License 2.0,
 * see http://www.apache.org/licenses/LICENSE-2.0
 */

package de.uhilger.servicehub.view;

import javax.swing.*;
import java.awt.Dimension;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.awt.BorderLayout;
import java.awt.Font;

/**
 * A panel to display license information of application FileManager.
 *
 * @author Ulrich Hilger, <a href="http://dev.uhilger.de" target="_blank">http://dev.uhilger.de</a>
 * @author Published under the terms and conditions of
 * the <a href="http://www.apache.org/licenses/LICENSE-2.0" target="_blank">Apache License 2.0</a>
*/

public class LicensePane extends JPanel {

  /* line separator character (sequence) */
  private String lineSeparator = System.getProperty("line.separator");

  /**
   * Create a new object of class <code>LicensePane</code>
   *
   * @param d  the preferred pane dimensions
   * @param licensePath  path to file with license information
   */
  public LicensePane(Dimension d, String licensePath) {
    /* create a text area to show the license text in */
    JTextArea licText = new JTextArea(getLicenseText(getClass().getResourceAsStream(licensePath)));
    licText.setEditable(false);
    licText.setFont(new Font("Courier", Font.PLAIN, 12));

    /* create a scroll pane as the license text is long */
    JScrollPane licPane = new JScrollPane();
    licPane = new JScrollPane(licText);
    licPane.setPreferredSize(d);
    licPane.setVerticalScrollBarPolicy(
                  JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    licPane.setHorizontalScrollBarPolicy(
                  JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

    /* add the scroll pane to this panel */
    setLayout(new BorderLayout());
    add(licPane, BorderLayout.CENTER);
    licText.setCaretPosition(0); // go to top of text (for JRE versions earlier than 1.4)
  }

  /**
   * Get the license text
   *
   * @return the license text
   */
  private String getLicenseText(InputStream is) {
    StringBuffer license = new StringBuffer();
    try {
      BufferedReader r = new BufferedReader(new InputStreamReader(is));
      String buf = r.readLine();
      while(buf != null) {
        license.append(buf);
        license.append(lineSeparator);
        buf = r.readLine();
      }
      r.close();
      is.close();
    }
    catch(Exception e) {
    	StringBuffer buf = new StringBuffer();
    	buf.append("The license text could not be opened.\n\n");
    	buf.append("You may want to obtain a complete distribution package ");
    	buf.append("at\nhttp://www.lightdev.com");
      JOptionPane.showMessageDialog(this, buf.toString());
    }
    return license.toString();
  }
}
